package com.biu.billiards.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.biu.billiards.config.BaseErrorEnum;
import com.biu.billiards.config.BaseException;
import com.biu.billiards.model.bo.MtBO;
import com.biu.billiards.model.entity.Goods;
import com.biu.billiards.model.entity.Mt;
import com.biu.billiards.model.vo.dy.DyGoodsVo;
import com.biu.billiards.model.vo.mqtt.OpenBilliardsVo;
import com.biu.billiards.model.vo.mt.GetMtVo;
import com.biu.billiards.service.impl.GoodsServiceImpl;
import com.dianping.openapi.sdk.api.customerauth.session.CustomerKeyShopScopeQuery;
import com.dianping.openapi.sdk.api.customerauth.session.entity.CustomerKeyShopScopeRequest;
import com.dianping.openapi.sdk.api.customerauth.session.entity.CustomerKeyShopScopeResponse;
import com.dianping.openapi.sdk.api.oauth.CustomerRefreshToken;
import com.dianping.openapi.sdk.api.oauth.entity.CustomerRefreshTokenResponse;
import com.dianping.openapi.sdk.api.oauth.entity.RefreshTokenRequest;
import com.dianping.openapi.sdk.httpclient.DefaultOpenAPIClient;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Component
public class MtUtils {

    private static GoodsServiceImpl goodsService;
    @Resource
    private GoodsServiceImpl rcsGoodsService;

    @PostConstruct
    public void init(){
        goodsService = rcsGoodsService;
    }

    public static void main(String[] args) {


        String refreshToken = getAuth2("3f19e710d7ac7723a8a54df308011f51c1951762");
        JSONObject jsonObject = getRefreshSession(refreshToken);

        System.out.println("dsadasdasdasf");
        System.out.println(jsonObject);

    }



    public static MtBO getTokenOrBid(GetMtVo getMtVo) {

        System.out.println("getTokenOrBid");

        String refreshToken = getAuth(getMtVo);

        JSONObject jsonObject = getRefreshSession(refreshToken);


        System.out.println(jsonObject.getString("token"));
        System.out.println(jsonObject.getString("bid"));

        String token = jsonObject.getString("token");
        String bid = jsonObject.getString("bid");

        MtBO mb = new MtBO();
        mb.setToken(token);
        mb.setBid(bid);

        mb.setAuthCode(getMtVo.getAuthCode());

        mb.setChangeTime(LocalDateTime.now());
        mb.setExpirationTime(LocalDateTime.now().plusDays(30));
        mb.setMtId(getMtVo.getMtId());
        mb.setShopId(getMtVo.getShopId());

        return mb;

    }

////        System.out.println("refreshToken");
////      //  System.out.println(jsonObject);
////        //{"bid":"cf6140304adedf051f405c7e4804fd93","token":"d3ba7668d8783383044383048c36bd6e7ae3d784"}
////        JSONObject jsonObject = new JSONObject();
////        jsonObject.put("token","d3ba7668d8783383044383048c36bd6e7ae3d784");
////        jsonObject.put("bid","cf6140304adedf051f405c7e4804fd93");
////
////        String openId = getOpen_shop_uuid(jsonObject);
////        //9db00e8fc3d8fa8d5d55e2c832c06497
////
////        System.out.println("openId");
////        System.out.println(openId);
//
//       // dyValid(openId,"d3ba7668d8783383044383048c36bd6e7ae3d784","d3ba7668d8783383044383048c36bd6e7ae3d784");
//
//
//        DyGoodsVo dyGoodsVo =new DyGoodsVo();
//        dyGoodsVo.setCode("6226666896");
//
//        //valid(dyGoodsVo);
//
//    }
//public static void main(String[] args) {
//
// //   getAuth("ea7aa5718d369f98e74c75b5146ceb438f91ba89");
//
//}


    public static String getAuth(GetMtVo getMtVo){

        Map<String, String> params = new HashMap<>();
        params.put("app_key", getMtVo.getMtKey());
        params.put("app_secret", getMtVo.getMtSecret());
        params.put("auth_code", getMtVo.getAuthCode());

        params.put("grant_type", "authorization_code");




        String tar = HttpClientUtil.doPost2("https://openapi.dianping.com/router/oauth/token",params);

        JSONObject jsonObject = JSON.parseObject(tar);


        System.out.println("dsadasfasfasfasf");
        System.out.println(jsonObject);
        System.out.println((String) jsonObject.get("refresh_token"));

        return (String) jsonObject.get("refresh_token");



    }



    public static String getAuth2(String authCode){

        Map<String, String> params = new HashMap<>();
        params.put("app_key", "fd60b92ed24ab145");
        params.put("app_secret", "74df60ccaf4247963a40586d8127776444f50ef2");
        params.put("auth_code", authCode);

        params.put("grant_type", "authorization_code");

        System.out.println("dasdasdasdasdasda");


        String tar = HttpClientUtil.doPost2("https://openapi.dianping.com/router/oauth/token",params);

        JSONObject jsonObject = JSON.parseObject(tar);


        System.out.println("dsadasfasfasfasf");
        System.out.println(jsonObject);
        System.out.println((String) jsonObject.get("refresh_token"));

        return (String) jsonObject.get("refresh_token");



    }

    public static String getOpen_shop_uuid(Mt mt){

//       String token = jsonObject.get("token").toString();
//        String bid = jsonObject.get("bid").toString();


        DefaultOpenAPIClient openAPIClient = new DefaultOpenAPIClient();

//        CustomerKeyShopScopeRequest request = new CustomerKeyShopScopeRequest("fd60b92ed24ab145",
//                "74df60ccaf4247963a40586d8127776444f50ef2",
//                token,bid);


        CustomerKeyShopScopeRequest request = new CustomerKeyShopScopeRequest(mt.getMtKey(),
                mt.getMtSecret(),
                mt.getToken(),mt.getBid());

        CustomerKeyShopScopeQuery shopScopeQuery = new CustomerKeyShopScopeQuery(request);
        CustomerKeyShopScopeResponse response = openAPIClient.invoke(shopScopeQuery);


        System.out.println("getOpen_shop_uuid");
        System.out.println(response);

        return response.getData().get(0).getOpen_shop_uuid();


    }





    //cf6140304adedf051f405c7e4804fd93

    public static JSONObject getRefreshSession(String token){
        JSONObject jsonObject = new JSONObject();

        DefaultOpenAPIClient openAPIClient = new DefaultOpenAPIClient();
        RefreshTokenRequest request = new RefreshTokenRequest("fd60b92ed24ab145","74df60ccaf4247963a40586d8127776444f50ef2",token);
        CustomerRefreshToken refreshToken = new CustomerRefreshToken(request);
        CustomerRefreshTokenResponse response = openAPIClient.invoke(refreshToken);

        jsonObject.put("token",response.getAccess_token());
        jsonObject.put("bid",response.getBid());

       return jsonObject;

    }






//    @PostConstruct
//    public void init(){
//        System.out.println("初始化了");
//        goodsService=rcsGoodsService;
//    }


    public static OpenBilliardsVo valid2(DyGoodsVo dyGoodsVo){

        OpenBilliardsVo openBilliardsVo = new OpenBilliardsVo();
        Goods goods = goodsService.selectGoodsSku("1234567");

        if (goods!=null){


            openBilliardsVo.setGoodsId(goods.getGoodsId());
            openBilliardsVo.setBilliardsNumber(dyGoodsVo.getBilliardsNumber());
            openBilliardsVo.setDeviceNumber(dyGoodsVo.getDeviceNumber());
            openBilliardsVo.setBilliardsId(dyGoodsVo.getBilliardsId());
            openBilliardsVo.setOpen(1);
            openBilliardsVo.setShopId(dyGoodsVo.getShopId());
            return openBilliardsVo;




        }


        return openBilliardsVo;

    }



    public static OpenBilliardsVo valid(DyGoodsVo dyGoodsVo, Mt mt){





        OpenBilliardsVo openBilliardsVo = new OpenBilliardsVo();


//
//        String token = "b2ee92fc1a6eea2529cfaefcbf25466ede1101c0";
//        String bid = "cf6140304adedf051f405c7e4804fd93";

//        String token = mt.getToken();
//        String bid = mt.getBid();

//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("token",token);
//        jsonObject.put("bid",bid);

        String openId = getOpen_shop_uuid(mt);

        JSONObject targetJson =  mtValid(openId,dyGoodsVo.getCode(),mt);

        if (targetJson.getInteger("code")==200){

            System.out.println("是20000");
            System.out.println(targetJson);
            Integer productId = targetJson.getJSONObject("data").getInteger("dealgroup_id");

            Goods goods = goodsService.selectGoodsSku(productId.toString());

            if (goods!=null){
                int nowHour = LocalDateTime.now().getHour();

                if ( nowHour>=goods.getStartTime()  && nowHour+1<=goods.getEndTime()){
                    openBilliardsVo.setGoodsId(goods.getGoodsId());
                    openBilliardsVo.setBilliardsNumber(dyGoodsVo.getBilliardsNumber());
                    openBilliardsVo.setDeviceNumber(dyGoodsVo.getDeviceNumber());
                    openBilliardsVo.setBilliardsId(dyGoodsVo.getBilliardsId());
                    openBilliardsVo.setOpen(1);
                    openBilliardsVo.setShopId(dyGoodsVo.getShopId());

                    if (confirm(openId,dyGoodsVo.getCode(),mt)){
                        return openBilliardsVo;
                    }

                }else {


                    throw new BaseException(BaseErrorEnum.goods_time_ERROR);
                }


            }else {


                throw new BaseException(BaseErrorEnum.goods_ERROR);
            }

        }

        return null;

    }

    public static JSONObject mtValid(String openId,String code,Mt mt){



        LocalDateTime now = LocalDateTime.now();
        String formatDateStr = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        Map<String, String> requestParam = new HashMap<>();
   //     requestParam.put("app_key", "fd60b92ed24ab145");
        requestParam.put("app_key",mt.getMtKey());
        requestParam.put("timestamp", formatDateStr);
        requestParam.put("format", "json");
        requestParam.put("v", "1");
        requestParam.put("sign_method", "MD5");
        requestParam.put("session", mt.getToken());
        requestParam.put("open_shop_uuid", openId);
        requestParam.put("receipt_code", code);

        try {
          //  requestParam.put("sign", SignUtil.signTopRequest(requestParam, "74df60ccaf4247963a40586d8127776444f50ef2", "MD5"));
            requestParam.put("sign", SignUtil.signTopRequest(requestParam, mt.getMtSecret(), "MD5"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }


         String tar = HttpClientUtil.doPost2("https://openapi.dianping.com/router/tuangou/receipt/prepare",requestParam);

        JSONObject jsonObject = JSON.parseObject(tar);


        System.out.println("tar1111");
        System.out.println(jsonObject);


        return jsonObject;




    }






    public static Boolean confirm(String openId,String code,Mt mt) {

        LocalDateTime now = LocalDateTime.now();
        String formatDateStr = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, String> requestParam = new HashMap<>();
        //requestParam.put("app_key", "fd60b92ed24ab145" );
        requestParam.put("app_key", mt.getMtKey() );

        requestParam.put("timestamp", formatDateStr);
        requestParam.put("format", "json");
        requestParam.put("v", "1");
        requestParam.put("sign_method", "MD5");
       // requestParam.put("session", token);
        requestParam.put("session", mt.getToken());
        requestParam.put("open_shop_uuid", openId);
        requestParam.put("receipt_code", code);
        requestParam.put("count", "1");

        requestParam.put("requestid", "12334");
        requestParam.put("app_shop_account", "123456");
        requestParam.put("app_shop_accountname", "test123");

        //验证签名，详情见签名生成说明文档
        try {
           // requestParam.put("sign", SignUtil.signTopRequest(requestParam, "74df60ccaf4247963a40586d8127776444f50ef2", "MD5"));
            requestParam.put("sign", SignUtil.signTopRequest(requestParam, mt.getMtSecret(), "MD5"));
        } catch (IOException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

        String str =HttpClientUtil.doPost2("https://openapi.dianping.com/router/tuangou/receipt/consume",requestParam);
        System.out.println("最终结果");

        JSONObject jsonObject =JSON.parseObject(str);

        System.out.println(jsonObject);

        if (jsonObject.getInteger("code")==200){
            return true;
        }else {
            return false;
        }



    }





}
